﻿/*******
 *    POST          http://localhost:9000/token
 *    Header        Content-Type: application/x-www-form-urlencoded
 *    Request Body  grant_type=password&UserName=aierchina\administrator&Password=pass@word1
 * *****/
namespace aier.wx.api.selfhost
{
    using aier.business.logic;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.OAuth;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web.Hosting;

    public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private UserBll userBll = null;
        public AuthorizationServerProvider(UserBll userBll)
        {
           
            this.userBll = userBll;
        }

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            await Task.Factory.StartNew(() => context.Validated());
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            await Task.Factory.StartNew(() => {

                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                //TODO 以后修改为CRM里的用户
                if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
                {
                    try
                    {

                        string userjson = userBll.ValidateUser(context.UserName, context.Password);

                        var identity = new ClaimsIdentity(context.Options.AuthenticationType);


                        identity.AddClaim(new Claim("UserIdentity", userjson));
                        identity.AddClaim(new Claim(ClaimTypes.Role, "read"));
                        identity.AddClaim(new Claim(ClaimTypes.Role, "write"));
                        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                        context.Validated(ticket);
                    }
                    catch (System.Exception ex)
                    {
                        context.SetError("出现错误", ex.Message);
                    }
                }
                else if(!string.IsNullOrWhiteSpace(context.UserName)) {
                    string userjson = userBll.ValidateEmployee(context.UserName);
                    if (!string.IsNullOrWhiteSpace(userjson))
                    {
                        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                        identity.AddClaim(new Claim("UserIdentity", userjson));
                        identity.AddClaim(new Claim(ClaimTypes.Role, "read"));
                        identity.AddClaim(new Claim(ClaimTypes.Role, "write"));
                        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                        context.Validated(ticket);
                    }
                    else {
                        context.SetError("invalid_grant", "The username or password is incorrect");
                    }

                    
                }
                else {
                    context.SetError("invalid_grant", "The username or password is incorrect");
                    return;
                }
            });
        }
    }
}
